package com.example.chat.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chat.domain.entity.ChatContent;
import com.example.chat.domain.entity.GroupMessage;
import com.example.chat.domain.entity.GroupUser;
import com.example.chat.domain.entity.User;
import com.example.chat.mapper.GroupMessageMapper;
import com.example.chat.service.GroupMessageService;
import com.example.chat.service.GroupUserService;
import com.example.chat.service.UserService;
import com.example.chat.utils.RedisConstants;
import com.example.chat.utils.SystemConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GroupMessageServiceImpl extends ServiceImpl<GroupMessageMapper, GroupMessage> implements GroupMessageService {

    @Resource
    private GroupUserService groupUserService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserService userService;

    private static final DefaultRedisScript<Void> test = new DefaultRedisScript<>();
    static {
        test.setLocation(new ClassPathResource("scripts/addGroupMessage.lua"));
        test.setResultType(Void.class);
    }

    @Override
    public Long saveGroupMessage(String msg, Long id, Long receiver) {

        GroupUser groupUser = groupUserService.lambdaQuery()
                .eq(GroupUser::getUserId, id)
                .eq(GroupUser::getGroupChatId, receiver).one();
        //表示被禁言
        if(Integer.valueOf(0).equals(groupUser.getStatus())){
            return 0L;
        }
        GroupMessage groupMessage = GroupMessage.builder()
                .userId(id)
                .groupChatId(receiver)
                .message(msg)
                .build();
        boolean save = save(groupMessage);
        Long msgId = groupMessage.getId();
        if(save){
            Set<String> idStr = stringRedisTemplate.opsForZSet()
                    .range(RedisConstants.CHAT_GROUP_USERS_ID+receiver, 0, -1);
            List<String> ids = idStr.stream().map(String::valueOf).collect(Collectors.toList());
            String time = LocalDateTime.now()
                    .format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
            List<String> args = List.of(receiver.toString(),msgId.toString(),
                    String.valueOf(System.currentTimeMillis()),msg,time);
            stringRedisTemplate.execute(test,ids,args.toArray());
        }
        return msgId;
    }

    @Override
    public ChatContent forWard(Long msgId, String message, Long currentUserId, Long receiver) {
        User user = userService.getById(currentUserId);
        //消息id,群聊Receiver,用户UserId,用户icon,消息内容text,时间time
        ChatContent chatContent = ChatContent.builder()
                .id(msgId)
                .Receiver(receiver)
                .userId(user.getId())
                .userName(user.getUserName())
                .groupIcon(SystemConstants.GROUPCHAT_ICON)
                .icon(user.getIcon())
                .time(LocalDateTime.now()
                        .format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")))
                .text(message)
                .build();
        return chatContent;
    }
}
